#!/usr/bin/python
# author: yoshiii.yoshiii@googlemail.com
# you found this code on http://yoshiii-box.googlecode.com/svn/ 
#
import Image, ImageFont, ImageDraw
import calendar, datetime
import gconf
import os, sys, random, time, tempfile

infile = random.choice(sys.argv[1:])
outfile = tempfile.mkstemp(".jpg", ".desktop-wallpaper-", os.path.expanduser("~"))[1]
date = datetime.datetime.now()
xoffset = 30
yoffset = 30
fontsize = 15
font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf", fontsize)

im = Image.open(infile)
draw = ImageDraw.Draw(im)

# TODO: scale image to screen size

# render calendar into image
(c_height, c_width) = font.getmetrics()		# get character dimenstions
day_str = " %i "%date.day
for line in calendar.month(date.year, date.month).split("\n"):
    line = " %s "%line
    if day_str in line:
	xpos = line.find(day_str)
	# xoffset + textwidth 
	xindent = xoffset + font.getsize(line[:xpos])[0]
	rect = ((xindent + c_width , yoffset),
		(xindent + font.getsize(day_str)[0] - c_width, yoffset + int(1.3*c_height)))
	draw.ellipse(rect, outline="rgb(255,0,0)", fill="rgb(0,0,255)")
	
    draw.text((xoffset, yoffset), line, font=font)
    yoffset += int(1.3 * c_height)

im.save(outfile)

# inspired by Davyd Madeley's wallpaperchanger
class GConfClient:
    def __init__(self):
        self.__client__ = gconf.client_get_default ()
	self.__background_path__ = "/desktop/gnome/background/picture_filename"
	self.__options_path__    = "/desktop/gnome/background/picture_options"
    def get_background(self):
        return self.__client__.get_string(self.__background_path__)
    def set_background(self, background):
        self.__client__.set_string(self.__background_path__, background)
    def set_option (self, option):
        self.__client__.set_string(self.__options_path__, option)
client = GConfClient()

# get old background image and clean up
old_bg_file = client.get_background()
try:
	os.remove(old_bg_file)
except OSError:
	pass

#print "old:", old_bg_file
#print "new:", outfile

# register new background image
client.set_background(outfile)

#client.set_option("wallpaper")
#client.set_option("centered")
#client.set_option("zoom")
#client.set_option("stretched")
client.set_option("scaled")

